package cnooc.mqtt;

import cn.hutool.core.util.StrUtil;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MqttClientService {

    private static final String BROKER_URI = "tcp://192.168.1.29:1883";
    private static final String CLIENT_ID = "springboot-client";
    private static final String SUBSCRIBE_TOPIC = "/edge///rtg";
    private static final String Publish_Topic = "/cloud///cmd/set";
    private static final String CONTROL_CMD = "{\"data\":[{\"d\":[{\"m\":\"yc26\",\"v\":\"{}\"}],\"dev\":\"{}\",\"ts\":1722245700}],\"type\":\"cmd/set\",\"pKey\":\"\",\"sn\":\"\",\"ts\":1722245700,\"ver\":\"2.1.0\"}";

    private MqttClient client;
    @Autowired
    private MessageArrivedCallback callback;
    @EventListener(ApplicationReadyEvent.class)
    public void init() {
        connectAndSubscribe();
    }

    private void connectAndSubscribe() {
        try {
            if (client == null) {
                client = new MqttClient(BROKER_URI, CLIENT_ID, new MemoryPersistence());
            }

            if (!client.isConnected()) {
                MqttConnectOptions options = new MqttConnectOptions();
                options.setCleanSession(true);
                options.setAutomaticReconnect(true); // 尽管加了这个，仍建议主动检测
                client.setCallback(callback);
                client.connect(options);
                client.subscribe(SUBSCRIBE_TOPIC);
                System.out.println("[MQTT] 已连接并订阅: " + SUBSCRIBE_TOPIC);
            }

        } catch (MqttException e) {
            System.err.println("[MQTT] 连接或订阅失败: " + e.getMessage());
        }
    }

    // 定时每5秒检查连接状态，断开就重连
    @Scheduled(fixedDelay = 5000)
    public void checkConnection() {
        if (client == null || !client.isConnected()) {
            System.out.println("[MQTT] 检测到断开，尝试重连...");
            connectAndSubscribe();
        }
    }

    /**
     *
     * @param devId 设备ID
     * @param status 更改的状态
     */
    public void publish(String devId, String status) {
        if (client != null && client.isConnected()) {
            try {
                String payload = StrUtil.format(CONTROL_CMD, devId, status);
                MqttMessage message = new MqttMessage(payload.getBytes());
                message.setQos(1);
                client.publish(Publish_Topic, message);
                System.out.println("[MQTT] 已发布消息到 " + Publish_Topic + " 内容: " + payload);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        } else {
            System.err.println("[MQTT] 客户端未连接，无法发送消息");
        }
    }
}
